<?php
/**
 * Created by PhpStorm.
 * User: ciwei
 * Date: 2017/12/4
 * Time: 13:16
 */
namespace app\index\model;

use think\Db;
use \think\Model;


class Answer extends Model
{
    protected static function init()
    {
        self::event('after_insert', function ($answer) {
            $num = db('answer')
                ->where('uid',session('uid'))
                ->where('ctime','>',time()-604800)
                ->count();
            db('user')->where('uid',session('uid'))->update(['answers'=>$num]);
            db('question')->where('qid',$answer->qid)->setInc('answer_num');
            $info['duid'] = db('question')->where('qid',$answer->qid)->find()['uid'];
            $info['suid'] = session('uid');
            $info['qid'] = $answer['qid'];
            $info['status'] = 0;
            $info['ctime'] = time();
            db('msg')->insert($info);

        });
    }
    public function getAnswer($qid)
    {
        $data = Db::table('answer')
            ->alias('a')
            ->join('user u','a.uid = u.uid')
            ->field('a.aid,a.content,a.status,a.ctime,a.zan_num,u.uid,u.nickname,u.face,u.role')
            ->where('a.qid',$qid)
            ->order('a.status desc,a.zan_num desc')
            ->select();
        return $data;
    }

    public function addAnswer($data)
    {
        unset($data['file']);
        $data['uid'] = session('uid');
        $res = Answer::save($data);
        if($res){
            exit(json_encode(['error'=>0,'info'=>'评论成功']));
        }else{
            exit(json_encode(['error'=>1,'info'=>'评论失败']));
        }
    }
    public function checkCaina($data)
    {
        $k1 = db('question')->where('qid',$data['qid'])->update(['status'=>1]);
        $k2 = db('answer')->where('aid',$data['aid'])->update(['status'=>1]);
        $k3 = db('user')->where('uid',$data['suid'])->setInc('kiss',$data['kiss']);

        if($k1&&$k2&&$k3){
            unset($data['kiss']);
            unset($data['aid']);
            $data['ctime'] = time();
            $data['status'] = 4;

            db('msg')->insert($data);
            exit(json_encode(['error'=>0,'info'=>'采纳成功']));
        }else{
            exit(json_encode(['error'=>1,'info'=>'采纳失败']));
        }
    }
}